package com.demo.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.demo.entity.AjaxResult;
import com.demo.entity.OrderLog;
import com.demo.entity.TbGoods;
import com.demo.mapper.TbGoodsMapper;
import com.demo.service.TbGoodsService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.BooleanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@RequiredArgsConstructor
public class TbGoodsServiceImpl implements TbGoodsService {

    @Autowired
    private TbGoodsMapper tbGoodsMapper;


    /**
     * 通过id查询商品
     *
     * @param goodsId
     * @return
     */
    @Override
    public AjaxResult findById(Long goodsId) {
        TbGoods tbGoods = tbGoodsMapper.selectById(goodsId);
        return AjaxResult.success(tbGoods);
    }

    /**
     * 修改库存
     *
     * @param tbGoods
     * @return
     */
    @Override
    public AjaxResult updateGoods(TbGoods tbGoods) {
        //A服务操作数据库 调用B服务  B服务抛异常
//        System.out.printf("1：A服务操作数据库 调用B服务  B服务抛异常");
//        int i = 1 / 0;
        boolean b = tbGoodsMapper.update(tbGoods.getGoodsId(), tbGoods.getGoodsStock()) > 0;
        if (BooleanUtils.isTrue(b)) {
            //A服务操作数据库 调用B服务操作数据库 然后抛异常
//            System.out.printf("2：A服务操作数据库 调用B服务操作数据库 然后抛异常");
//            int i = 1 / 0;
            return AjaxResult.success();
        }
        return AjaxResult.error("更新失败");
    }

    /**
     * 添加商品
     *
     * @param tbGoods
     * @return
     */
    @Override
    public AjaxResult insertGoods(TbGoods tbGoods) {
        tbGoods.setGoodsId(IdWorker.getId());
        tbGoods.setGoodsTime(new Date());
        int b = tbGoodsMapper.insert(tbGoods);
        if (BooleanUtils.isTrue(b > 0)) {
            return AjaxResult.success("商品添加成功");
        }
        return AjaxResult.error("商品添加失败");
    }

    /**
     * 记录日志
     * @param orderLog
     * @return
     */
    @Override
    public AjaxResult saveLog(OrderLog orderLog) {
        int i  =  tbGoodsMapper.saveLog(orderLog);
        if (BooleanUtils.isTrue(i>0)){
            return AjaxResult.success("日志记录成功");
        }
        return AjaxResult.error("日志记录失败");
    }
}
